package com.example.myapplication.net;

import android.util.Log;

import com.example.myapplication.BuildConfig;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    private static volatile  RetrofitClient retrofitClient;
    private ApiService apiService;
    private String URL = "";
    private RetrofitClient(){

    }
    private static  RetrofitClient getInstance(){
        if(retrofitClient == null){
            synchronized (RetrofitClient.class){
                if(retrofitClient == null){
                    retrofitClient = new RetrofitClient();
                }
            }
        }
        return  retrofitClient;
    }
    private Interceptor getHeaderInterceptor(){
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuider = original.newBuilder()
                .header("token","");
                Request request = requestBuider.build();
                return chain.proceed(request);
            }
        };
    }
    private Interceptor getInterceptor(){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                if(BuildConfig.DEBUG){
                    Log.i("OKHttps", message);
                }
            }
        });
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return  interceptor;
    }
    public ApiService getApi(){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .addInterceptor(getHeaderInterceptor())
                .addInterceptor(getInterceptor())
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        apiService = retrofit.create(ApiService.class);
        return  apiService;
    }
}
